package com.itheima.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.BaseContextUtils;
import com.itheima.common.RelationException;
import com.itheima.dao.OrdersDao;
import com.itheima.domain.*;
import com.itheima.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {

    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;

    /**
     * 支付功能
     * @param orders
     */
    @Transactional
    @Override
    public void submit(Orders orders) {
        //获取用户id
        Long userId = BaseContextUtils.getId();
        //生成订单号
        long number = IdWorker.getId();
        //查询用户表
        User user = userService.getById(userId);
        //查询地址表
        LambdaQueryWrapper<AddressBook> lqw =new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,userId);
        lqw.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(lqw);
        if (addressBook==null){
            throw new RelationException("地址为空，不能下单");
        }
        //查询购物车表
        LambdaQueryWrapper<ShoppingCart> lqwShop = new LambdaQueryWrapper<>();
        lqwShop.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shopList = shoppingCartService.list(lqwShop);
        if (shopList==null || shopList.size()==0){
            throw new RelationException("购物车为空，不能下单");
        }
        //操作数据
        AtomicInteger count = new AtomicInteger(0);//复看
        List<OrderDetail> list =  shopList.stream().map((item)->{
            // 设置订单详细表属性
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(item.getName());
            orderDetail.setOrderId(number);
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            count.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());//复看
            return orderDetail;
        }).collect(Collectors.toList());
        //设置 下单表相关的值
        orders.setId(number);
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(number));
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setOrderTime(LocalDateTime.now());
        orders.setAmount(new BigDecimal(count.get()));//总金额
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setStatus(2);
        orders.setUserName(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        // 添加下单表数据
        this.save(orders);
        // 添加下单详情表数据
        orderDetailService.saveBatch(list);
        //清空购物单
        shoppingCartService.remove(lqwShop);
    }
}
